
var express = require('express')
var router = express.Router();
var User = require('../model/User')
var Category = require('../model/Category')
var Artcle = require('../model/Artcle')
const jwtDcoded = require('jwt-decode')
var bcrypt = require('bcryptjs')

var passport = require('passport');
//获取用户信息
router.get('/', passport.authenticate('jwt', {
    session: false
}), async (req, res) => {
    let token = req.headers.authorization
    let info = jwtDcoded(token)
    if (info.isAdmin) {
        const data = {}
        const users = await User.find()
        const total = await User.countDocuments()
        data.users = users
        data.total = total
        res.json({ msg: '获取数据成功', data })
    } else {
        res.json({
            type: 'error',
            msg: '您没有权限'
        })
    }
})
//操作用户帐号是否可登录
router.put('/roles/:id', passport.authenticate('jwt', {
    session: false
}), (req, res) => {
    let token = req.headers.authorization
    let info = jwtDcoded(token)
    if (info.isAdmin) {
        User.findById({
            _id: req.params.id
        }).then(user => {
            if (user.isAdmin) {
                res.json({
                    type: 'error',
                    msg: '管理员账户不可禁用',
                    isAdmin: user.isAdmin
                })
                return false
            }
            User.updateOne({ _id: req.params.id }, { isStatus: req.body.isStatus }).then(result => {
                res.json({
                    type: 'success',
                    msg: '权限操作成功',
                    isAdmin: user.isAdmin
                })
            })
        })
    } else {
        res.json({
            type: 'error',
            msg: '您没有权限'
        })
    }
})
//获取分类列表
router.get('/category', passport.authenticate('jwt', {
    session: false
}), (req, res) => {
    let token = req.headers.authorization
    let info = jwtDcoded(token)
    if (info.isAdmin) {
        Category.find().then(result => {
            res.json(result)
        })
    } else {
        res.json({
            type: 'error',
            msg: '您没有权限'
        })
    }
})
//修改分类
router.put('/category/:id', passport.authenticate('jwt', {
    session: false
}), (req, res) => {
    let token = req.headers.authorization
    let info = jwtDcoded(token)
    if (info.isAdmin) {
        Category.updateOne({ _id: req.params.id }, { name: req.body.name }).then(result => {
            res.json({
                type: 'success',
                msg: '分类修改成功'
            })
        })
    } else {
        res.json({
            type: 'error',
            msg: '您没有权限'
        })
    }
})

//文章发布
router.post('/write', passport.authenticate('jwt', {
    session: false
}), (req, res) => {
    var add = new Artcle({
        title: req.body.title,
        description: req.body.description,
        content: req.body.content,
        user: req.body.userId,
        category: req.body.category,
        isCaogao: req.body.isCaogao,
        artcleImg: req.body.artcleImg
    })
    add.save().then(result => {
        res.json({
            type: 'success',
            msg: "文章已发布，待管理员审核"
        })
    })
})
//文章保存草稿
router.post('/save', passport.authenticate('jwt', {
    session: false
}), (req, res) => {
    var add = new Artcle({
        title: req.body.title,
        description: req.body.description,
        content: req.body.content,
        user: req.body.userId,
        category: req.body.category,
        isCaogao: req.body.isCaogao,
        artcleImg: req.body.artcleImg
    })
    add.save().then(result => {
        res.json({
            type: 'success',
            msg: "文章已保存草稿箱"
        })
    })
})
//所有文章查询
router.get('/AllAcrticle', passport.authenticate('jwt', {
    session: false
}), (req, res) => {
    let token = req.headers.authorization
    let info = jwtDcoded(token)
    let query = req.query.query

    if (info.isAdmin) {
        Artcle.find().populate(['category', 'user']).then(result => {
            if (!query) {
                res.json(result.filter((item) => {
                    return item.isCaogao == true
                }))
            } else {
                res.json(result.filter((item) => {
                    return item.isCaogao == true && item.user.username == query
                }))
            }
        })
    }
    else {
        res.json({
            type: 'error',
            msg: '您没有权限'
        })
    }

})
//获取我的文章
router.get('/MyArticle', passport.authenticate('jwt', {
    session: false
}), (req, res) => {
    let token = req.headers.authorization
    let info = jwtDcoded(token)
    let query = req.query.query || '1'
    Artcle.find().populate(['category', 'user']).then(result => {
        //全部
        if (query == '1') {
            res.json(result.filter((item) => {
                return item.user._id == info.id
            }))
            return false
        }
        //草稿
        if (query == '2') {
            res.json(result.filter((item) => {
                return item.user._id == info.id && item.isCaogao == false
            }))
            return false
        }
        //待审核
        if (query == '3') {
            res.json(result.filter((item) => {
                return item.user._id == info.id && item.isCaogao == true && item.isStatus == false
            }))
            return false
        }
        //已发布
        if (query == '4') {
            res.json(result.filter((item) => {
                return item.user._id == info.id && item.isStatus == true
            }))
            return false
        }
    })

})
//编辑我的文章
router.put('/edit/:id', passport.authenticate('jwt', {
    session: false
}), (req, res) => {
    console.log(req.params.id)
    console.log(req.body)
    Artcle.updateOne({ _id: req.params.id }, {
        title: req.body.title,
        category: req.body.category,
        artcleImg: req.body.artcleImg,
        content: req.body.content,
        description: req.body.description
    }).then(result => {
        res.json({
            type: 'success',
            msg: '文章编辑成功'
        })
    })
})
//删除文章
router.delete('/deletd/:id', passport.authenticate('jwt', {
    session: false
}), (req, res) => {

    Artcle.findOneAndDelete({ _id: req.params.id }).then(result => {
        res.json({
            type: 'success',
            msg: '删除成功'
        })
    })

})
//我的文章发布
router.put('/fabu/:id', passport.authenticate('jwt', {
    session: false
}), (req, res) => {
    Artcle.updateOne({ _id: req.params.id }, { isCaogao: true }).then(result => {
        res.json({
            type: 'success',
            msg: '发布成功，请管理员审核'
        })
    })
})
//获取待审核文章列表
router.get('/CheckArticle', passport.authenticate('jwt', {
    session: false
}), (req, res) => {
    let token = req.headers.authorization
    let info = jwtDcoded(token)
    let query = req.query.query
    console.log(info)
    if (info.isAdmin) {
        Artcle.find().populate(['category', 'user']).then(result => {
            if (!query) {
                res.json(result.filter((item) => {
                    console.log(item)
                    return item.isCaogao == true && item.isStatus == false
                }))
            } else {
                res.json(result.filter((item) => {
                    console.log(item)
                    return item.isCaogao == true && item.isStatus == false && item.user.username == query
                }))
            }

        })
    } else {
        res.json({
            type: 'error',
            msg: '您没有权限'
        })
    }
})
//审核发布文章
router.put('/checkFabu/:id', passport.authenticate('jwt', {
    session: false
}), (req, res) => {
    let token = req.headers.authorization
    let info = jwtDcoded(token)
    if (info.isAdmin) {
        Artcle.updateOne({ _id: req.params.id }, { isStatus: true }).then(result => {
            res.json({
                type: 'success',
                msg: '文章已发布'
            })
        })

    } else {
        res.json({
            type: 'error',
            msg: '您没有权限'
        })
    }
})
//修改密码
router.put('/editPass', passport.authenticate('jwt', {
    session: false
}), (req, res) => {
    let token = req.headers.authorization
    let info = jwtDcoded(token)
    let oldPassword = req.body.oldPassword

    User.findOne({ _id: info.id }).then(users => {
        // console.log(users.password)
        bcrypt.compare(oldPassword, users.password).then(isMatch => {

            if (isMatch) {
                let salt = bcrypt.genSaltSync(10);
                let hash = bcrypt.hashSync(req.body.newPassword, salt);
                User.updateOne({ _id: info.id }, { password: hash }).then(result => {
                    res.json({ type: 'success', msg: '密码修改成功' })
                })
            } else {
                res.json({ type: 'error', msg: '您的旧密码错误' })
            }
        })
    })
})



//展示页获取所有分类
router.get('/cate', (req, res) => {
    Category.find().then(result => {
        res.json(result)
    })
})
//展示页获取文章
router.get('/showA', (req, res) => {

    let query = req.query.query


    Artcle.find().populate(['category', 'user']).then(result => {
        // console.log(query)
        if (!query) {
            // console.log(1)
            res.json(result.filter((item) => {
                return item.isStatus == true
            }))
        } else {
            res.json(result.filter((item) => {
                return item.isStatus == true && item.category.name == query
            }))
        }
    })

})
module.exports = router